package cn.dhnep.demo.controller;

import cn.dhnep.demo.pojo.Picture;
import cn.dhnep.demo.pojo.Result;
import cn.dhnep.demo.service.PictureService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author 邱文彬
 * @Date 2021/11/5 11:49
 * @Version 1.0
 */


@Controller
@ResponseBody
@CrossOrigin
@Api("轮播图功能")
public class pictureController {

    //    设置上传文件的最大值
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;
    //    设置上床文件的类型
    public static final List<String> AVATAR_TYPE = new ArrayList<>();

    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmg");
        AVATAR_TYPE.add("image/gif");

    }

    @Autowired
    private PictureService pictureService;

    @ApiOperation("上传图片功能接口")
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public Result insert(@RequestParam("file") MultipartFile file,
                         HttpSession session, HttpServletRequest request,
                         @RequestParam("filename") String filename,
                         @RequestParam("pictureOfficialAccountUrl") String pictureOfficialAccountUrl,
                         @RequestParam("pictureDetails") String pictureDetails) throws IOException {


//        判断文件是否为空
        if (file.isEmpty()) {
            return new Result(10001, "未接收到图片", null);
        }
//        判断文件的大小是否超出限制
        if (file.getSize() > AVATAR_MAX_SIZE) {
            return new Result(10002, "文件大小超出上传最大值", null);
        }

//        判断文件的类型是否是规定的类型
        String contentType = file.getContentType();
//        如果集合包含某个元素则返回true
        if (!AVATAR_TYPE.contains(contentType)) {
            return new Result(10003, "文件类型不支持", null);
        }

//        设置将来要存放的目录


        File directory = new File(new File(ResourceUtils.getURL("").getPath()) + "/src/main/resources/static/upload");
        System.out.println(directory.toString());

//        将一个File指向这个路径,判断是有该文件,如果没有则创建
        File dir = new File(directory.toString());
        System.out.println(dir.toString());
//        判断是否存在,不存在则创建目录
        if (!dir.exists()) {
            dir.mkdirs();
            System.out.println("不存在,创建成功");
        }
//        获取到这个文件的名称,UUID工具来将生成一个新的字符创作为文件名
        String originalFilename = file.getOriginalFilename();


        int index = originalFilename.lastIndexOf(".");


        String suffix = originalFilename.substring(index);

        String filename2 = UUID.randomUUID().toString().toUpperCase() + suffix;

        File dest = new File(dir, filename2); // 是一个空文件
//        将file的数据写入到这个空文件中

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return new Result(10004, "保存图片时发生异常", null);
        }
        Integer openId = getuidFromSession(session);
        String accountName = getUsernameFromSession(session);
        String pictureName = (String) session.getAttribute("picture_name");
        System.out.println("用户ID : " + openId);
        System.out.println("用户姓名 :" + accountName);



        String URLName = request.getScheme() + "://" + getNowIP2() + ":" + request.getServerPort() + "/" + "upload/" + filename2;
        int code = pictureService.uploadPicture(openId, accountName, URLName, pictureName, filename, pictureOfficialAccountUrl, pictureDetails);

        if (code > 0) {
            return new Result(0, "上传成功", null);
        } else {
            return new Result(10005, "上传失败", null);
        }

    }


    //    给前端传送需要展示的图片
    @ApiOperation("获取可以展示的图片url与绑定的url")
    @RequestMapping(value = "/picture/getPicture", method = RequestMethod.GET)
    public Result getPicture(ServletRequest req) {
        HttpServletRequest request = (HttpServletRequest) req;
        String url1 = request.getRequestURI();
        String url2 = url1.substring(0, url1.indexOf("/"));

        System.out.println(url2);
        List<Picture> pictures = pictureService.getPicture();
        if (pictures != null) {
            return new Result(0, "获取图片成功", pictures);
        } else {
            return new Result(10001, "获取图片失败", null);
        }
    }


    //    将图片设置成展示,需要姓名参数(picture_name)
    @ApiOperation("将图片设置为是否展示")
    @RequestMapping(value = "setExhibition", method = RequestMethod.POST)
    public Result setExhibition(@RequestParam("pictureName") String pictureName) {

        int i = pictureService.setExhibition(pictureName);
        if (i > 0) {
            return new Result(0, "设置成功", null);
        } else {
            return new Result(10001, "设置失败,可能为展示图片超上限", null);
        }
    }
    //    将图片设置不成展示,需要姓名参数(picture_name)
    @ApiOperation("将图片设置为是否展示")
    @RequestMapping(value = "getExhibition", method = RequestMethod.POST)
    public Result getExhibition(@RequestParam("pictureName") String pictureName) {

        int i = pictureService.getExhibition(pictureName);
        if (i > 0) {
            return new Result(0, "设置成功", null);
        } else {
            return new Result(10001, "设置失败,可能为展示图片超上限", null);
        }
    }

    //    获取全部图片
    @ApiOperation("获取全部图片")
    @RequestMapping(value = "getPictureAll", method = RequestMethod.POST)
        public Result getPictureAll()  {

        Map<String, Picture> pictures = pictureService.getPictureAll();
        if (pictures != null) {
            return new Result(0, "获取图片成功", pictures);
        } else {
            return new Result(10001, "获取图片失败", null);
        }
    }

    //    获取页面展示的图片个数
    @ApiOperation("获取页面展示图片的个数")
    @RequestMapping(value = "getTheNumberOfPictures", method = RequestMethod.POST)
    public Integer getTheNumberOfPictures() {
        Integer number = pictureService.getTheNumberOfPictures();
        return number;
    }

    //    覆盖图像功能
    @ApiOperation("覆盖功能")
    @RequestMapping(value = "cover", method = RequestMethod.POST)
    public Result cover(@RequestParam("oldpictureName") String oldpictureName, @RequestParam("newpictureName") String newpictureName) {
        pictureService.setPictureState(oldpictureName, newpictureName);
        return new Result(0, "更新成功", null);
    }

    //    修改图片绑定的url
    @ApiOperation("修改图片绑定的url")
    @RequestMapping(value = "bindingUrl", method = RequestMethod.POST)
    public Result bindingUrl(@RequestParam("pictureName") String pictureName, @RequestParam("pictureTestUrl") String pictureTestUrl) {

        Integer code = pictureService.bindingUrl(pictureName, pictureTestUrl);
        if (code > 0) {
            return new Result(0, "更新成功", null);
        } else {
            return new Result(10001, "更新失败", null);
        }
    }
    //    根据图片名称删除
    @ApiOperation("根据图片名称删除")
    @RequestMapping(value = "deletePicture", method = RequestMethod.POST)
    public Result bindingUrl(@RequestParam("pictureName") String pictureName) {

        Integer code = pictureService.deletePircture(pictureName);
        if (code > 0) {
            return new Result(0, "删除成功", null);
        } else {
            return new Result(10001, "删除失败", null);
        }
    }

    public static Integer getuidFromSession(HttpSession session) {
        Integer openId = (Integer) session.getAttribute("open_id");
        return openId;
    }

    public static String getUsernameFromSession(HttpSession session) {
        String accountName = (String) session.getAttribute("account_name");
        return accountName;
    }

    private static String getNowIP2() throws IOException {
        String ip = null;
        BufferedReader br = null;
        try {
            URL url = new URL("https://v6r.ipip.net/?format=callback");
            br = new BufferedReader(new InputStreamReader(url.openStream()));
            String s = "";
            StringBuffer sb = new StringBuffer("");
            String webContent = "";
            while ((s = br.readLine()) != null) {
                sb.append(s + "\r\n");
            }
            webContent = sb.toString();
            int start = webContent.indexOf("(") + 2;
            int end = webContent.indexOf(")") - 1;
            webContent = webContent.substring(start, end);
            ip = webContent;
        } finally {
            if (br != null)
                br.close();
        }
        if (StringUtils.isEmpty(ip)) {
            throw new RuntimeException();
        }
        return ip;
    }
}
